#if UNITY_EDITOR
using FibMatrix.Task;

namespace FibMatrix
{
    [FM_Mono.IgnoreGen]
    public class AssetDBAsyncLoadAssetPipe : IResourceLoadPipe
    {
        public AssetDBAsyncLoadAssetPipe()
        {
        }

        public FMTask Handle(IResourcePipelineContext context, out ResourceError error)
        {
            error = ResourceError.None;

            DefaultLoadItem mainHint = context.item as DefaultLoadItem;

            if (mainHint.assetHandle == null)
            {
                ++mainHint.objRefCount;
                mainHint.assetHandle = new AssetDBUAssetLoadHandle(
                    new AssetDBFakeResRequest(mainHint.itemID, context.type ?? typeof(UnityEngine.Object))
                    );
            }

            FMTask task = null;
            if (!mainHint.assetHandle.isCompleted)
            {
                task = PooledAsyncFMTask.Allocate(mainHint, null, GenerateAssetAsyncWork, 
                    GetAsyncAssetWorkError, null);
            }
            else
            {
                task = PooledCallLaterFMTask.Allocate(1);
            }
            task.Begin();
            return task;
        }

        private static ResourceError GetAsyncAssetWorkError(PooledAsyncFMTask task, IAsyncBase asyncWork)
        {
            var loadHandle = (asyncWork as AssetDBUAssetLoadHandle);
            if (loadHandle == null || loadHandle.asset == null)
                return ResourceError.AssetLoadError;

            return ResourceError.None;
        }

        private static IAsyncBase GenerateAssetAsyncWork(PooledAsyncFMTask task)
        {
            DefaultLoadItem item = (task.context as DefaultLoadItem);
            return item.assetHandle;
        }
    }
}
#endif